/*
 * Copyright (c) 2019, Waterbell and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 */
package com.shuiqinling.ww.android.Util;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.util.Log;

import com.shuiqinling.ww.android.AndroidDirectCall;
import com.shuiqinling.ww.android.Util.HttpUtil.HttpCallback;
import com.shuiqinling.ww.android.alipay.AliPay;
import com.shuiqinling.ww.android.cn00.R;
import com.shuiqinling.ww.android.cn00.wxapi.WXPayEntryActivity;
import com.shuiqinling.ww.android.cn00.wxapi.WeChat;
import com.tencent.mm.sdk.modelpay.PayReq;

public class PayHelper {

	private static final String MSG_TYPEKEY_PAY_RESULT = "pay_result";

	private static final int HTTP_STATUS_OK = 200;

	private static final String PAY_ORDER_CREATE = "http://10.0.0.3:8080/bellpay/order/create";
	private static final String PAY_ORDER_UPDATE = "http://10.0.0.3:8080/bellpay/order/update";

	public static final int CHANNEL_ID_ALIPAY = 101;
	public static final int CHANNEL_ID_WEXIN = 102;

	//测试支付
	public static void pay(final Activity ctx, final int channelID, HashMap<String, String> params) {

		String date = GetDataNow();

		// 准备信息
		final Map<String, Object> requestParamsMap = new Hashtable<String, Object>();
		requestParamsMap.put("itemid", "106");
		requestParamsMap.put("cid", "1");
		requestParamsMap.put("uid", "2");
		requestParamsMap.put("zid", "3");
		requestParamsMap.put("rid", "4");
		requestParamsMap.put("date", date);
		requestParamsMap.put("sign", Utils.generateHash(date + "aP5SXrfXcJeFVW3r", "MD5"));

		switch (channelID) {
		case CHANNEL_ID_ALIPAY:
			requestParamsMap.put("paytype", "2");
			new Thread(new Runnable() {

				@Override
				public void run() {

					UIHelper.ShowWaitDialog();
					// "http://10.0.0.3:8080/bellpay/order/create"
					try {
						HttpUtil.DoPost(PAY_ORDER_CREATE, requestParamsMap, new HttpCallback() {

							@Override
							public void OnHttpResponse(int ResponceCode, String content) {
								UIHelper.HideWaitDialog();
								if (ResponceCode == HTTP_STATUS_OK) {
									doPay(ctx, channelID, content);
								} else {
									UIHelper.ShowToast(ctx.getResources().getString(R.string.pay_order_failed));
								}
							}

						});
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}).start();
			break;
		case CHANNEL_ID_WEXIN:
			requestParamsMap.put("paytype", "1");
			new Thread(new Runnable() {

				@Override
				public void run() {

					UIHelper.ShowWaitDialog();
					try {
						HttpUtil.DoPost(PAY_ORDER_CREATE, requestParamsMap, new HttpCallback() {

							@Override
							public void OnHttpResponse(int ResponceCode, String content) {
								UIHelper.HideWaitDialog();
								if (ResponceCode == HTTP_STATUS_OK) {
									doPay(ctx, channelID, content);
								} else {
									UIHelper.ShowToast(ctx.getResources().getString(R.string.pay_order_failed));
								}
							}
						});
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}).start();
			break;
		}

	}

	public static void doPay(Activity ctx, int channelID, String content) {
		switch (channelID) {
		case CHANNEL_ID_ALIPAY:
			try {
				JSONObject json = new JSONObject(content);
				if (json.get("ECode").toString().equals("")) {
					String orderInfo = json.getString("OrderInfo");
					String sign = json.getString("Sign");
					String outTradeNo = json.getString("OutTradeNo");
					AliPay.doPay(outTradeNo, orderInfo, sign);
				} else {
					UIHelper.ShowToast(ctx.getResources().getString(R.string.pay_order_failed));
				}
			} catch (JSONException e) {
				UIHelper.ShowToast(ctx.getResources().getString(R.string.pay_order_failed));
			}
			break;

		case CHANNEL_ID_WEXIN:
			try {
				JSONObject json = new JSONObject(content);
				if (json.get("ECode").toString().equals("")) {

					PayReq req = new PayReq();
					// req.appId = "wxf8b4f85f3a794e77"; // 测试用appId
					req.appId = json.getString("AppID");
					req.partnerId = json.getString("PartnerID");
					req.prepayId = json.getString("PrepayID");
					req.nonceStr = json.getString("Noncestr");
					req.timeStamp = json.getString("Timestamp");
					req.packageValue = json.getString("PackAge");
					req.sign = json.getString("Sign");
					req.extData = "app data"; // optional
					WXPayEntryActivity.tradeNo = json.getString("OrderNO");
					// 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
					// UIHelper.ShowToast(ctx,
					// Boolean.toString(req.checkArgs()));
					WeChat.pay(req);
					UIHelper.ShowToast(ctx.getResources().getString(R.string.pay_order_wx));
				} else {
					UIHelper.ShowToast(ctx.getResources().getString(R.string.pay_order_failed));
				}
			} catch (JSONException e) {
				UIHelper.ShowToast(ctx.getResources().getString(R.string.pay_order_failed));
			}

			break;
		}

	}

	@SuppressLint("SimpleDateFormat")
	private static String GetDataNow() {
		// 生成订单号
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
		String date = sdf.format(new Date(System.currentTimeMillis()));
		return date;
	}

	//仅供测试使用
	public static void serverNotify(final Activity ctx, String outTradeNo, String resultStatus) {
		String date = GetDataNow();

		final Map<String, Object> requestParamsMap = new Hashtable<String, Object>();
		requestParamsMap.put("orderno", outTradeNo);
		requestParamsMap.put("returncode", resultStatus);
		requestParamsMap.put("date", date);
		requestParamsMap.put("sign", Utils.generateHash(date + "aP5SXrfXcJeFVW3r", "MD5"));

		new Thread(new Runnable() {

			@Override
			public void run() {

				UIHelper.ShowWaitDialog();
				// "http://10.0.0.3:8080/bellpay/order/create"
				try {
					HttpUtil.DoPost(PAY_ORDER_UPDATE, requestParamsMap, new HttpCallback() {

						@Override
						public void OnHttpResponse(int ResponceCode, String content) {
							UIHelper.HideWaitDialog();
						}

					});
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

	public static void notifyUnity(String errCode) {
		// build message json
		// {
		// "type": "mail", //所属类型
		// "event": "NEW_MAIL" //该类型的事件名
		// }
		Log.w("Pay","notifyUnity");
		HashMap<String, String> paramData=new HashMap<String, String>();
		paramData.put("event", errCode);
		AndroidDirectCall.SendMessageToUnity(MSG_TYPEKEY_PAY_RESULT, paramData);
				

	}
}
